﻿#!/usr/bin/env python3
# _*_ coding:utf-8 _*_
'''
@File    :   daka_main_project.py
@Time    :   2022/02/02 15:24:36
@Author  :   chou 
@Version :   1.0
@Contact :   chou2079986882@gmail.com
@Desc    :   None
'''


import requests
import os
import sys
import time
import json
import pandas as pd
from selenium import webdriver
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
from hashlib import md5
import pymysql
import pandas as pd
from main_project import sql_insert
import random
from main_project import push


headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36"
}
url1 = ' https://wxyqfk.zhxy.net/?yxdm=10623#/login'
url2 = 'https://wxyqfk.zhxy.net/?yxdm=10623#/clockIn'


def login():
    global data_login
    data_login = {
        "Name": stu_name,
        "PassWord": stu_sign_password,
        "UserType": "1",
        "XGH": stu_xgh,
        "YXDM": "10623"
    }
    login_url = "https://wxyqfk.zhxy.net/?yxdm=10623#/login"
    # 登陆
    s = requests.Session()
    s.post(login_url, json=data_login, headers=headers)
    # post登陆页面
    login_result = s.post("https://yqfkapi.zhxy.net/api/User/CheckUser")
    print(login_result)
    return s

# ddddocr接口


def new_ocr():
    pic1 = requests.get('https://yqfkapi.zhxy.net/api/common/getverifycode')
    tex1 = pic1.content
    tex2 = bytes.decode(tex1)
    if json.loads(tex2)['info'] == '非法访问！':
        print(tex2)
        sys.exit(1)
    tex3 = json.loads(tex2)['data']['img']
    key = json.loads(tex2)['data']['key']
    url = 'data:image/png;base64,' + tex3
    # print(url)
    # print(qr_key)
    # 1.识别验证码
    img_url = url
    from ddddocr_NB import free
    from urllib.request import urlretrieve
    urlretrieve(img_url, './qrcode_temp.png')
    filepath = "./qrcode_temp.png"
    code = free(filepath)
    # code="1234"
    print(code)
    print("调用了免费接口（ddddocr接口）")
    return key, code


# post数据部分
def health_daka(s, key, code):
    data_health = {
        "UID": stu_uid,
        "UserType": "1",
        "JWD": JWD,
        "key": key,
        "code": code,
        "ZZDKID": "37",
        "A1": "正常",
        "A4": "无",
        "A2": "全部正常",
        "A3": Place,
        "A11": "不在校",
        "A12": "未实习",
        "A13": "低风险区",
        "YXDM": "10623",
        "version": "v1.3.2"
    }

    # for i in range(2):
    health_url = 'https://wxyqfk.zhxy.net/?yxdm=10623#/clockIn'
    s.post(health_url, headers=headers)
    health_result = s.post(
        'https://yqfkapi.zhxy.net/api/ClockIn/Save', data=data_health, headers=headers)


# 浏览器操作部分driver = webdriver_holdon()
def webdriver_holdon():
    print("开始操作浏览器")
    chromedriver1 = "./chromedriver"
    options = Options()
    options.add_argument('--no-sandbox')
    options.add_argument('--headless')  # 无头参数
    options.add_argument('--disable-gpu')
    # 启动浏览器
    driver = Chrome(executable_path=chromedriver1, options=options)
    print("浏览器设置完成")

    # driver = webdriver.Chrome(chrome_options=chrome_options,executable_path=chromedriver)
    print("打开浏览器成功")
    time.sleep(1)
    driver.get("https://wxyqfk.zhxy.net/?yxdm=10623#/login")
    time.sleep(2)
    XGH = driver.find_element_by_xpath(
        '''//input[starts-with(@placeholder,'请输入学号')]''')
    XGH.click()
    XGH.send_keys(data_login['XGH'])
    print("输入了学号:"+data_login['XGH'])
    Name = driver.find_element_by_xpath(
        '''//input[starts-with(@placeholder,'请输入姓名')]''')
    Name.click()
    Name.send_keys(data_login['Name'])
    print("输入了姓名:"+data_login['Name'])
    Password = driver.find_element_by_xpath(
        '''//input[starts-with(@placeholder,'请输入密码')]''')
    Password.click()
    Password.send_keys(data_login['PassWord'])
    print("输入了密码:"+data_login['PassWord'])
    time.sleep(1)
    login_button = driver.find_element_by_xpath(
        '''//button[starts-with(@class,'sign-in-btn')]''')
    login_button.click()
    print("点击了登陆")
    time.sleep(2)
    driver.get("https://wxyqfk.zhxy.net/?yxdm=10623#/clockIn")
    print("进入到-打卡页面成功")
    time.sleep(1)
    return driver


def uid():
    formdata = {
        "YXDM": "10623",
        "UserType": "1",
        "XGH": stu_xgh,
        "Name": stu_name,
        "PassWord": stu_password
    }
    url = "https://yqfkapi.zhxy.net/api/User/CheckUser"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"}
    response = requests.post(url, json=formdata, headers=headers)
    # 使用json()方法，将response对象，转为列表/字典
    json_response = response.json()
    # print(json_response)
    # 获取UID
    UID = json_response['data']['ID']
    # print(UID)
    stu_uid = str(UID)
    return stu_uid


def insert_one():
    # 1.连接
    conn = pymysql.connect(host='localhost', user='daka',
                           password='1234c', db='daka')
    # print(conn)
    if conn:
        print("连接数据库成功")
    else:
        print('连接数据库失败')
    # 2.创建游标
    cursor = conn.cursor()

    # 使用 execute() 方法执行 SQL，如果表存在则删除
    sql = "INSERT INTO fall(stu_name,stu_num,password,email,jwd,place) VALUES('%s','%s','%s','%s','%s','%s')" % (
        stu_name, stu_xgh, password, to_addr, JWD, Place)
    cursor.execute(sql)

    cursor.close()
    print("执行完成")


def all_data():
    # 1.连接

    conn = pymysql.connect(host='localhost', user='daka',
                           password='1234c', db='daka')
    sql_query = 'SELECT * FROM user'
    table = pd.read_sql(sql_query, con=conn)
    conn.close()
    table.drop_duplicates(['stu_num', 'stu_name'], keep='last')
    # print(df)
    return table


def recode(a):
    # time.sleep(3)
    # 记录日志
    if a == "success":
        print(stu_name + "打卡成功")
        sql_query2 = f"delete from fall where stu_name='{stu_name}'"
        sql_insert(sql_query=sql_query2)
        print("已在fall数据表删除此人数据")

    else:
        print(stu_name + "打卡失败")
        sql_query_de = f"DELETE from fall WHERE(stu_num='{stu_xgh}')"
        sql_insert(sql_query=sql_query_de)
        insert_one()
        push(text=f"{stu_name} 打卡失败😓【主程序通知】")
    try:
        driver.close()
    except:
        print("进入下一个打卡")

    randomInt = random.randint(0, 5)  # 通过函数返回指定闭区间内的随机数
    print("将等待：" + str(randomInt) + " 秒")
    time.sleep(randomInt)  # 通过函数阻塞指定秒数


if __name__ == '__main__':
    lis = []
    table = all_data()
    for i in range(table.shape[0]):
        data = table.loc[i]
        lis.append(dict(data))
    for i in lis:
        # 姓名
        stu_name = str(i['stu_name'])
        # 学号
        stu_xgh = str(i['stu_num'])
        # 密码
        password = str(i['password'])
        stu_password = md5(password.encode('utf8')).hexdigest()

        # JWD = str(i['JWD'])
        JWD = str(i['jwd'])
        Place = str(i['place'])
        to_addr = str(i['email'])
        # phone = str(int(i['phone']))
        a = 'fall'
        print("打卡数据载入成功！")
        print("获取uid中----")
        stu_uid = uid()
        if stu_uid:
            print(stu_name+"UID："+stu_uid)
            stu_sign_password = str(i['password'])  # 登录密码
            # print(stu_name, stu_password, stu_xgh, stu_uid, JWD, Place)
            try:
                s = login()
                print("request请求成功")
            except:
                print("登录失败")
            try:
                driver = webdriver_holdon()
                print("selenium请求成功")
            except:
                print("webdriver操作失败")
            # 检测是否打卡
            try:
                print("检查打卡情况")
                if driver.find_element_by_class_name('already-title'):
                    print(stu_name + "今天已打卡")
                    driver.close()
                    a = "success"
            except:
                try:
                    key, code = new_ocr()
                    time.sleep(1)
                    if len(code) == 4 and code.isalnum():
                        health_daka(s, key, code)
                        a = "success"
                        driver.refresh()
                        if driver.find_element_by_class_name('already-title'):
                            print(stu_name + "今天已打卡")
                            # email_send_right(stu_xgh, to_addr)
                            driver.close()
                            a = "success"
                        else:
                            continue
                    else:
                        key, code = new_ocr()
                        time.sleep(1)
                        if len(code) == 4 and code.isalnum():
                            health_daka(s, key, code)
                            a = "success"
                            driver.refresh()
                            if driver.find_element_by_class_name('already-title'):
                                print(stu_name + "今天已打卡")
                                # email_send_right(stu_xgh, to_addr)
                                driver.close()
                                a = "success"

                            else:
                                a = 'wrong'
                except:
                    a = 'wrong'
                    # driver.close()
        else:
            print("uid获取失败")
            a = 'wrong'

        try:
            driver.close()
        except:
            print("已关闭浏览器")

        try:
            recode(a)
        except:
            print("发生严重错误，暂时未解决")
